package com.njuse.jvmfinal.Instruction;

import java.nio.ByteBuffer;

import com.njuse.jvmfinal.memory.jclass.Field;
import com.njuse.jvmfinal.memory.jclass.JClass;
import com.njuse.jvmfinal.memory.jclass.Method;
import com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.constant.Constant;
import com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.constant.ref.FieldRef;
import com.njuse.jvmfinal.memory.jclass.runtimeConstantPool.constant.ref.MethodRef;
import com.njuse.jvmfinal.runtimestructure.Jframe;

public class PUTSTATIC extends Instruction {
	private int index;
	
	public  void readindex(ByteBuffer reader) {
		this.index=(int)reader.getShort();
	}
	
	public  void execute(Jframe frame) {
        JClass clazz = frame.getMymethod().getClazz();
        Constant fieldRef = clazz.getRuntimeConstantPool().getConstant(this.index);
        Field field = ((FieldRef) fieldRef).findfield();
        String descriptor = field.getDescriptor();
        int position=field.getPosition();
        JClass target=field.getClazz();

        if (target.isInitok()==false) {
        	frame.setPc(frame.getPc()-3);
        	target.init(frame.getMythread());
        	return;
        }
        Object[] targetvars=target.getStatics();
        Object[] managestack=frame.getManagestack();
        int top=frame.getStacktop();
        switch (descriptor.charAt(0)) {
        case 'Z':
        case 'B':
        case 'C':
        case 'S':
        case 'I':
        case 'F':
        case 'L':
        case '[':	
            Object tempint=managestack[top-1];
            top--;
            targetvars[position]=tempint;
            break;
        case 'J':
        case 'D':
            Object temphigh=managestack[top-1];
            Object templow=managestack[top-2];
            top=top-2;
            targetvars[position]=templow;
            targetvars[position+1]=temphigh;            
            break;
        }
        frame.setStacktop(top);
        target.setStatics(targetvars);
	}
}
